
class Ws {
    constructor() {
        let loginFrom = new Date().valueOf();

        //  这里是要修改地址信息的
        //this.url = "ws://gateway.wsdchigh.top:81/ws/ws/ksv.do?loginFrom="+loginFrom+"&token=";
        this.url = "wss://ssl.wsdchigh.top:6039/ws/ksv.do?loginFrom="+loginFrom+"&token=";
        this.map = new Map();
    }

    //  链接
    connect(token){
        let that = this;
        this.websocket = new WebSocket(this.url+token)
        this.websocket.onopen = event => {
            console.log(event)
            that.map.forEach((v,k) => {
                if(v.open && typeof v.open === 'function'){
                    v.open();
                }
            })

            //  定时(15s)发送心跳消息
            that.interval = setInterval(() => {
                that.websocket.send(JSON.stringify({
                    type:'echo'
                }));
                console.log("echo echo echo")
            },1000 * 15)
        }

        this.websocket.onclose = event => {
            //  暂时不重连
            console.log(event)

            that.map.forEach((v,k) => {
                if(v.close && typeof v.close === 'function'){
                    v.close();
                }
            })

            clearInterval(that.interval)
        }

        this.websocket.onmessage = event => {
            //console.log(event.data)
            that.map.forEach((v,k) => {
                if(v.cb.message && typeof v.cb.message === 'function'){
                    let d = JSON.parse(event.data);
                    if(v.filter(d.type)){
                        v.cb.message(d)
                    }
                }
            })
        }
    }

    //  注册   需要指定那些消息
    register(name,cb,filter){
        if(filter == null){
            filter = (t) => {
                return true;
            }
        }
        this.map.set(name,{
            cb:cb,
            filter:filter
        });
    }

    unregister(name){
        this.map.delete(name);
    }
}


export default Ws;